from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse, NoReverseMatch
from treemenus.models import Menu, MenuItem

class AbstractMenuItem(models.Model):
    """
    Abstract contentpages menu item
    """
    menu_item = models.OneToOneField(MenuItem, related_name='extension', editable=False)
    #enabled = models.BooleanField(_('Enabled'), default=True)
    view = models.CharField(_('View function'), max_length=50, blank=True)
    view_item = models.CharField(_('View item function'), max_length=50, blank=True)
    custom_title  = models.CharField(_('Special title'), max_length=512, blank=True)
    content  = models.TextField(_('Primary content'), blank=True)
    meta_keywords = models.TextField(_('Meta keywords'), blank=True)
    meta_description = models.TextField(_('Meta description'), blank=True)

    def __unicode__(self):
        return unicode(self.menu_item.id)
    
    @classmethod
    def get_by_menuitem(cls, menu_item):
        try:
            obj = cls.objects.get(menu_item=menu_item.id)
        except:  # TODO type
            obj = cls()
            obj.menu_item = menu_item
            obj.save()
        return obj
                
    @property            
    def url(self):
        if not hasattr(self, '_url'):
            self._url = self.menu_item.named_url and \
                reverse(self.menu_item.named_url) or self.menu_item.url
        return self._url

    @property            
    def self_or_child_url(self):
        """Self url or first url from children"""
        if self.menu_item.url:
            return self.menu_item.url
        
        for child in self.menu_item.children():
            url = self.get_by_menuitem(child).url
            if url: return url
            
        return ''
    
    @property            
    def menu_title(self):
        return self.menu_item.caption
    
    @property
    def page_title(self):
        return self.custom_title or self.menu_title     

    title = menu_title
                        
    def children(self):
        _children = self.__class__.objects.filter(menu_item__parent=self).order_by('menu_item__rank')
        return _children      
        
    class Meta:
        abstract = True
        verbose_name = _('page')  
        verbose_name_plural = _('pages')
        
# hack to translate treemenus
_('menu item')
_('menu items')